#!/usr/bin/env python
import sys
sys.path.append("/work/opt/analytic/my_python/lib")
from format_time import *
from HandleMysql import *
from switch_code import *
from jpype import *
import glob
import re
import math
import os

class Service58(object):
    def __init__(self):
        self.jars = ':'.join(glob.glob('./java_lib/*.jar'))
        #self.jars +=':'+':'.join(glob.glob('./local/*.jar'))
        startJVM(getDefaultJVMPath(),"-ea","-Djava.class.path=%s" % self.jars)
        self.NearDistrictService=JClass("com.bj58.groupbuy.location.NearDistrictService")
        self.nds=self.NearDistrictService()
        self.nds.init()
    
    def get_circle_list(self,lat,lon):
        self.lat=lat
        self.lon=lon
        self.circle_list=self.nds.getNearDistricts(self.lat,self.lon)
        return self.circle_list

def get_latitude_and_longitude():
    hm=HandleMysql('10.3.13.26',58885,'groupbug58_rsbo','IU(7vFIUsbo','dbwww58com_groupbuy_v2');
    hm.connect()
    results=hm.get_results("select latitude,longitude,id,parentid from partner where longitude<>'' and latitude<>''")
    return results

#id,partner_id,partner_parent_id,latitude,longitude,displocalid,displocalname,distance

def get_rad(d):
    return d * math.pi/180.0;Service58

def get_distance(lat1,lon1,lat2,lon2):
    rad_lat1=get_rad(lat1)
    rad_lon1=get_rad(lon1)
    rad_lat2=get_rad(lat2)
    rad_lon2=get_rad(lon2)
    rad_lat=rad_lat1-rad_lat2
    rad_lon=rad_lon1-rad_lon2
    d=2 * math.asin(math.sqrt(math.pow(math.sin(rad_lat/2),2)+math.cos(rad_lat1) * math.cos(rad_lat2) * math.pow(math.sin(rad_lon/2),2)))
    EARTH_RADIUS_METER=6378137.0
    return d * EARTH_RADIUS_METER;

def handle_circle(lat,lon,circle_list):
    my_list=[]
    for cl in circle_list:
        clat,clon=float(cl.getLatitude()),float(cl.getLongitude())
        distance=get_distance(float(lat),float(lon),clat,clon)
        my_list.append([cl.getDispLocalID(),convert_key(cl.getLocalName(),code='utf-8'),clat,clon,distance])
    new_list=sorted(my_list,key=lambda a:a[4],reverse=False)
    if len(new_list)<=5:
        return new_list
    else:
        return new_list[0:5]

def merge_list(list1,list2):
    my_dict={}
    for i in range(0,len(list1)):
        if not my_dict.has_key(list1[i]):
            my_dict[list1[i]]=list2[i]
    return my_dict

def get_circle_info(file):
    results=get_latitude_and_longitude()
    s58=Service58()
    #hm=HandleMysql('192.168.11.40','58885','root','group_buytj1140','dbwww58com_groupbuy_stats')
    #hm.connect()
    f=open(file,'w')
    for result in results:
        lat,lon=result[0],result[1]
        if not re.match(r'[\d\.]{1,}',lat):
            continue
        if not re.match(r'[\d\.]{1,}',lon):
            continue
        gcl=s58.get_circle_list(lat,lon)
        new_list=handle_circle(lat,lon,gcl)
        for nl in new_list:
	    nl.insert(0,result[3])
            nl.insert(0,result[2])
	    #fs=['partner_id','partner_parent_id','circle_latitude','circle_longitude','circle_id','circle_name','distance']
            #record=merge_list(fs,nl)
            #hm.insert_record('partner_circle',record)
            f.write(','.join([str(n) for n in nl])+"\n")

def load_data(file):
    import perl
    INC=perl.get_ref("@INC")
    INC.append("/work/opt/analytic/lib")
    perl.require("HandleDB")
    perl.call("HandleDB::connect_db","dbwww58com_groupbuy_stats","10.3.13.27","58885","root","group_buytj1140")
    fs=['partner_id','partner_parent_id','circle_id','circle_name','circle_latitude','circle_longitude','distance'];
    perl.call("HandleDB::load_data",file,'partner_circle',fs,',')   
 
def main():
    file='partner_circle.csv'
    get_circle_info(file)
    #os.system("perl load_data.pl %s" % file)
    load_data(file)
    
if __name__=="__main__":
    main()
